package genericinterfacedemo;


import java.util.ArrayList;
import java.util.List;

class Animal {
    protected String alias;

    public Animal(String alias) {
        this.alias = alias;
    }
}

class Cat extends Animal {
    public Cat(String alias) {
        super(alias);
    }

    @Override
    public String toString() {
        return "Cat{" +
                "alias='" + alias + '\'' +
                '}';
    }
}

class Dog extends Animal {
    public Dog(String alias) {
        super(alias);
    }

    @Override
    public String toString() {
        return "Dog{" +
                "alias='" + alias + '\'' +
                '}';
    }
}

public class GenericUpLowDemo {

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();

        List<Dog> dogs = new ArrayList<Dog>();
        dogs.add(new Dog("旺财"));
        List<Cat> cats = new ArrayList<Cat>();
        cats.add(new Cat("Tom"));
        //定义下界，只能接收Dog或者是Dog的父类的集合
        List<? super Dog> list1 = dogs;
        List<? super Dog> list2 = animalList;
        list2.add(new Dog("黑贝")); //下界只能添加Dog或者Dog的子类对象。
        //List<? super Dog> list3 = cats; //错误。

        for (Object obj : list2) { //下界遍历只能使用Object.
            System.out.println(obj);
        }

        //定义上界，只能接收Animal或者是Animal的子类
        List<? extends Animal> animals1 = animalList;
        List<? extends Animal> animals2 = dogs;
        List<? extends Animal> animals3 = cats;

        //注意：上界的集合是只读的，不能添加。
        //animals2.add(new Dog("黑贝")); //注意上界集合不能添加
        for (Animal a : animals2) {
            System.out.println(a);
        }
    }
}
